package com.dshore.messagecenter.dao.topicqueue;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.dshore.messagecenter.model.basedata.MdApp;
import com.dshore.messagecenter.model.system.SysDict;
import com.dshore.messagecenter.model.topicqueue.MdTopic;
import com.dshore.messagecenter.model.topicqueue.MdTopicAccess;
import com.dshore.messagecenter.model.topicqueue.MdTopicSend;
import com.dshore.messagecenter.util.UUIDUtil;


/**
 * 目标应用
 *
 */
@Repository
public class TopicSendDao {

	@Autowired
	JdbcTemplate jdbcTemplate;
	
	
	/** 根据编码和目标应用编号具体Send信息*/
	public List<MdTopicSend> querySendData(String topicQueueNo, String tAppId) {
		String sql = " select send.*, send.TARGET_APPID as TARGET_APP_ID, app.QUEUE_KEY as queueKey "
				+ " from T_MD_TOPIC_SEND send "
				+ " LEFT JOIN T_MD_APP app "
				+ " ON send.TARGET_APPID = app.ID "
				+ " where send.TOPIC_QUEUE_NO = ? and send.DEL_FLAG = 0 and app.APP_CODE = ?";
		RowMapper<MdTopicSend> rowMapper = new BeanPropertyRowMapper<>(MdTopicSend.class);
		return jdbcTemplate.query(sql,rowMapper,topicQueueNo,tAppId);
	}
	
	/**查询目标应用(charts用)*/
	public List<Map<String, Object>> queryTargetAppAndQueueName(String topicQueueNo) {
		String sql = "SELECT app.ID,app.APP_NAME,send.QUEUE_NAME from T_MD_APP app" + 
					" LEFT JOIN T_MD_TOPIC_SEND send" + 
					" ON app.ID = send.TARGET_APPID" + 
					" where send.TOPIC_QUEUE_NO = ? and send.DEL_FLAG = 0";
		try {
			return jdbcTemplate.queryForList(sql,topicQueueNo);
		} catch (Exception e) {
			return null;
		}
		
	}
	
	
	public List<MdApp> queryTargetAppByQueueSign(String topicQueueNo) {
		String sql = " SELECT ID,APP_NAME from T_MD_APP where ID in " + 
					"( SELECT TARGET_APPID FROM T_MD_TOPIC_SEND where TOPIC_QUEUE_NO = ? and DEL_FLAG = 0)";
		RowMapper<MdApp> rowMapper = new BeanPropertyRowMapper<>(MdApp.class);
		return jdbcTemplate.query(sql,rowMapper, topicQueueNo);
	}
	/**
	 * 查询多个目标应用id
	 */
	public List<Map<String, Object>> queryByTopicSign(String topicQueueNo) {
		String sql = " SELECT TARGET_APPID,QUEUE_NAME from T_MD_TOPIC_SEND where TOPIC_QUEUE_NO = ? and DEL_FLAG = 0";
		return jdbcTemplate.queryForList(sql,topicQueueNo);
	}
	
	public MdApp queryTargetApp(String targetId) {
		String sql = " SELECT ID,APP_NAME,QUEUE_KEY from T_MD_APP where ID = ?";
		RowMapper<MdApp> rowMapper = new BeanPropertyRowMapper<>(MdApp.class);
		return jdbcTemplate.queryForObject(sql,rowMapper, targetId);
	}
	
	public MdApp getApp(String targetAppId) {
		String sql = " SELECT * from T_MD_APP where ID = ? ";
		return jdbcTemplate.queryForObject(sql, MdApp.class, targetAppId);
	}
	/**查询发送方式
	 * 
	 * @return
	 */
	public List<SysDict> selectBySendType() {
		String sql = "SELECT dict_name,dict_code from t_sys_dict where dict_type='send_type'";
		RowMapper<SysDict> mcAPPRowMapper = new BeanPropertyRowMapper<>(SysDict.class);
		return jdbcTemplate.query(sql, mcAPPRowMapper);
	}
	
	/**
	 * 保存目标应用
	 */
	public Integer saveTApp(String id, int delFlag, String topicQueueNo, String targetId,int SEQ) {
		String sql ="insert into T_MD_TOPIC_SEND (ID,CREATED_TIME,MODIFIED_TIME,"
				+ " DEL_FLAG,TOPIC_QUEUE_NO,TARGET_APPID,SEQ) " 
				+ "values (?, ?, ?, ?, ?, ? ,?) ";
		return jdbcTemplate.update(sql,id,new Date(),new Date(),delFlag,topicQueueNo,targetId,SEQ);
	}
	
	/**
	 * 遍历删除send
	 */
	public int deleteSendByQueueSigns(String[] qSigns) {
	   final List<String> updateParams=new ArrayList<>();
	   for(String qSign : qSigns) {
		   updateParams.add(qSign);
		}
		String sql= "update T_MD_TOPIC_SEND set DEL_FLAG=1, MODIFIED_TIME=? where TOPIC_QUEUE_NO =?";	
		int[] execute = jdbcTemplate.batchUpdate(sql,new BatchPreparedStatementSetter() {
			
			@Override
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				ps.setTimestamp(1, new Timestamp(System.currentTimeMillis()));//第一个传数据库的时间
				ps.setString(2, updateParams.get(i));//
			}			
			@Override
			public int getBatchSize() {
				return updateParams.size();
			}
		});
		return execute.length;
	}
	/**
	 * 保存目标应用
	 */
	public int[] saveService(List<MdTopicSend>mdTopicSends) {
		String sql ="insert into T_MD_TOPIC_SEND (ID,CREATED_TIME,MODIFIED_TIME,"
				+ " DEL_FLAG,TOPIC_QUEUE_NO,SEND_TYPE,TARGET_APPID,TARGET_URL,SEQ,SEND_CONFIG) " 
				+ "values (?, ?, ?, ?, ?, ? ,? ,? ,? ,? ) ";
		return jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
			@Override
			public void setValues(PreparedStatement pstat, int i)
					throws SQLException {
				MdTopicSend mdTopicSend = mdTopicSends.get(i);
				pstat.setString(1, UUIDUtil.getUUId());
				pstat.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
				pstat.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
				pstat.setInt(4, 0);
				pstat.setString(5, mdTopicSend.getTopicQueueNo());
				pstat.setString(6, mdTopicSend.getSendType());
				pstat.setString(7, mdTopicSend.getTargetAppId());
				pstat.setString(8, mdTopicSend.getTargetUrl());
				pstat.setInt(9, mdTopicSend.getSeq());
				pstat.setString(10, mdTopicSend.getSendConfig());
			}
 
			@Override
			public int getBatchSize() {
				// 设置本批次一共多少组数据，隐含的就是循环几次
				return mdTopicSends.size();
			}
		});
	}
	
	/**
	 * 保存目标应用
	 */
	public int[] saveTopicSend(List<MdTopicSend> mdTopicSends) {
		String sql ="insert into T_MD_TOPIC_SEND (ID,CREATED_TIME,MODIFIED_TIME,"
				+ " DEL_FLAG,TOPIC_QUEUE_NO,QUEUE_NAME,SEND_TYPE,TARGET_APPID,TARGET_URL,SEQ) " 
				+ "values (?, ?, ?, ?, ?, ?, ? ,? ,? ,? ) ";
		List<Object[]> records = new ArrayList<Object[]>();
		Date now = new Date();
		for (MdTopicSend mdTopicSend : mdTopicSends) {
			records.add(new Object[]{UUIDUtil.getUUId(), now, now, 0, mdTopicSend.getTopicQueueNo(),
					mdTopicSend.getQueueName(),mdTopicSend.getSendType(),mdTopicSend.getTargetAppId(),mdTopicSend.getTargetUrl(),mdTopicSend.getSeq()});
		}
		return jdbcTemplate.batchUpdate(sql, records);
	}
	
	/**
	 * 修改时查询主题信息
	 */
	public MdTopic selectByTopic(String id) {
		String sql = "SELECT t.ID,t.TOPIC_QUEUE_NAME,t.TEMPLATE_ID,e.TEMPLATE_NAME  templateName,t.status from T_MD_TOPIC t left join T_MD_TEMPLATE e on t.TEMPLATE_ID=e.id where t.id= ? and t.DEL_FLAG=0";
		RowMapper<MdTopic> rowMapper = new BeanPropertyRowMapper<>(MdTopic.class);
		return jdbcTemplate.queryForObject(sql,rowMapper, id);
	}
	/**
	 * 修改时查询源应用
	 */
	public MdTopicAccess selectByTopicAccess(String topicQueueNo) {
		String sql = "SELECT A.ID,A.ACCESS_APPID,P.APP_NAME accessAppName from T_MD_TOPIC_ACCESS A  "+
						"LEFT JOIN T_MD_APP P ON A.ACCESS_APPID=P.ID where TOPIC_QUEUE_NO=? and A.DEL_FLAG=0";
		RowMapper<MdTopicAccess> rowMapper = new BeanPropertyRowMapper<>(MdTopicAccess.class);
		return jdbcTemplate.queryForObject(sql,rowMapper,topicQueueNo);
	}
	/**
	 * 修改时查询目标应用
	 */
	public List<MdTopicSend> selectByServiceAccess(String topicQueueNo) {
		String sql = "SELECT A.ID,A.TARGET_APPID targetAppId,P.APP_NAME targetAppName,"+
        "A.TARGET_URL,S.DICT_NAME sendName,A.SEND_TYPE from T_MD_TOPIC_SEND A  LEFT JOIN T_MD_APP P ON A.TARGET_APPID=P.ID "+
		"LEFT JOIN T_SYS_DICT S ON S.DICT_CODE=A.SEND_TYPE "+
        "where A.TOPIC_QUEUE_NO=? and A.DEL_FLAG=0 order by A.SEQ" ;
		RowMapper<MdTopicSend> rowMapper = new BeanPropertyRowMapper<>(MdTopicSend.class);
		return jdbcTemplate.query(sql,rowMapper,topicQueueNo);
	}
	/**
	 * 更新查询主题信息
	 */
	public Object UpdateByTopic(MdTopic mdTopic) {
		String sql = "update T_MD_TOPIC set MODIFIED_TIME=?,TOPIC_QUEUE_NAME=?,TEMPLATE_ID=? where id = ?";
		return jdbcTemplate.update(sql,new Date(),mdTopic.getTopicQueueName(),mdTopic.getTemplateId(),mdTopic.getId());
	}
	/**
	 * 更新查询主题信息
	 */
	public Object UpdateByTopicAccess(MdTopicAccess mdTopicAccess) {
		String sql = "update T_MD_TOPIC_ACCESS set ACCESS_APPID = ?,MODIFIED_TIME=? where id = ?";
		return jdbcTemplate.update(sql,mdTopicAccess.getAccessAppid(),new Date(),mdTopicAccess.getId());
	}
	/**
	 * 修改时删除目标应用
	 */
	public Object UpdateByServiceAccess(String topicQueueNo) {
		String sql = "update T_MD_TOPIC_SEND set DEL_FLAG=1 where TOPIC_QUEUE_NO = ?";
		return jdbcTemplate.update(sql, topicQueueNo);
	}
	//校验名称是否重复
	public List<MdTopic> selectBycheckName(String name) {
		String sql = "SELECT ID,TOPIC_QUEUE_NAME from T_MD_TOPIC where TOPIC_QUEUE_NAME= ? and DEL_FLAG=0";
		RowMapper<MdTopic> rowMapper = new BeanPropertyRowMapper<>(MdTopic.class);
		return jdbcTemplate.query(sql, rowMapper, name);
	}
	//校验编码是否重复
	public int selectByCode(String topicQueueNo) {
		String sql = "SELECT count(1) from T_MD_TOPIC where TOPIC_QUEUE_NO= ? and DEL_FLAG=0";
		return jdbcTemplate.queryForObject(sql, Integer.class, topicQueueNo);
	}
	//校验接入表编码
	public int selectByAccessCode(String topicQueueNo) {
		String sql = "SELECT count(1) from T_MD_TOPIC_ACCESS where TOPIC_QUEUE_NO= ? and DEL_FLAG=0";
		return jdbcTemplate.queryForObject(sql, Integer.class, topicQueueNo);
	}
	/**
	 * 查看服务接入配置
	 */
	//主题信息
	public MdTopic selectByTopicConfig(String id) {
		String sql = "SELECT p.ID,p.TOPIC_QUEUE_NO,p.TOPIC_QUEUE_NAME,p.ACCESS_TYPE,p.VHOST_NAME,p.TEMPLATE_ID,t.TEMPLATE_NAME templateName from T_MD_TOPIC p left join T_MD_TEMPLATE t on p.TEMPLATE_ID=t.ID where p.id= ? and p.DEL_FLAG=0";
		RowMapper<MdTopic> rowMapper = new BeanPropertyRowMapper<>(MdTopic.class);
		return jdbcTemplate.queryForObject(sql, rowMapper, id);
	}
	//源应用
	public MdTopicAccess selectByTopicAccessConfig(String TopicQueueNo) {
		String sql = "SELECT A.ACCESS_URL,A.ID,A.TOPIC_QUEUE_NO,A.ACCESS_APPID,P.APP_NAME accessAppName,P.APP_CODE accessAppCode,P.QUEUE_KEY queueKey from T_MD_TOPIC_ACCESS A LEFT JOIN T_MD_APP P ON A.ACCESS_APPID=P.ID where A.TOPIC_QUEUE_NO= ? and A.DEL_FLAG=0";
		RowMapper<MdTopicAccess> rowMapper = new BeanPropertyRowMapper<>(MdTopicAccess.class);
		return jdbcTemplate.queryForObject(sql, rowMapper, TopicQueueNo);
	}
	
	 //查询目标应用
	 
	public List<MdTopicSend> selectByServiceAccessConfig(String topicQueueNo) {
		String sql = "SELECT A.ID,A.TARGET_APPID targetAppId,P.APP_NAME targetAppName,P.APP_CODE targetAppCode,"+
        "A.TARGET_URL,P.QUEUE_KEY queueKey,S.DICT_NAME sendName,A.SEND_TYPE from T_MD_TOPIC_SEND A  LEFT JOIN T_MD_APP P ON A.TARGET_APPID=P.ID "+
		"LEFT JOIN T_SYS_DICT S ON S.DICT_CODE=A.SEND_TYPE   "+
        "where A.TOPIC_QUEUE_NO=? and A.DEL_FLAG=0 order by A.SEQ" ;
		RowMapper<MdTopicSend> rowMapper = new BeanPropertyRowMapper<>(MdTopicSend.class);
		return jdbcTemplate.query(sql,rowMapper,topicQueueNo);
	}
	
	/**获取KPI数据(只获取当前最近的数据，每个时间点的数据都不一样，无需加总求和)*/
	public List<Map<String, Object>> getCurrentInfo(String queueName) {
		String sql = "select CUR.KPI_CODE,CUR.KPI_VALUE,CUR.OBJ,dict.DICT_NAME,CUR.CREATED_TIME " + 
				" from T_MR_KPI_RECORD_CURRENT CUR LEFT JOIN T_SYS_DICT dict " + 
				" ON CUR.KPI_CODE = dict.DICT_CODE " + 
				" where CUR.OBJ_TYPE='1704' and dict.DICT_TYPE='kpi_type' and CUR.OBJ = ? " + 
				" and CUR.CREATED_TIME = ( " + 
				" select MAX(CUR.CREATED_TIME) " + 
				" from T_MR_KPI_RECORD_CURRENT CUR LEFT JOIN T_SYS_DICT dict " + 
				" ON CUR.KPI_CODE = dict.DICT_CODE " + 
				" where CUR.OBJ_TYPE='1704' and dict.DICT_TYPE='kpi_type' and CUR.OBJ = ? ) ";
		return jdbcTemplate.queryForList(sql, queueName, queueName);
	}
	
	/** 获取最近的统计时间 */
	public String getStaticTime(String obj) {
		String sql = "select MAX(TO_CHAR(CUR.CREATED_TIME,'yyyy-mm-dd hh24:mi:ss')) " + 
				" from T_MR_KPI_RECORD_CURRENT CUR LEFT JOIN T_SYS_DICT dict " + 
				" ON CUR.KPI_CODE = dict.DICT_CODE " + 
				" where CUR.OBJ_TYPE='1704' and dict.DICT_TYPE='kpi_type' and CUR.OBJ = ? ";
		return jdbcTemplate.queryForObject(sql, String.class, obj);
	}

	public String selectByStatus(String id) {
		String sql = "SELECT STATUS from T_MD_TOPIC where ID= ? ";
		return jdbcTemplate.queryForObject(sql, String.class, id);
	}
	/**
	 * 批量删除
	 */
	public int[] deleteTopicSend(List<MdTopicSend> mdTopicSends) {
		String sql ="update T_MD_TOPIC_SEND set DEL_FLAG=1 where ID = ?";
		List<Object[]> records = new ArrayList<Object[]>();
		for (MdTopicSend mdTopicSend : mdTopicSends) {
			records.add(new Object[]{mdTopicSend.getId()});
		}
		return jdbcTemplate.batchUpdate(sql, records);
	}
 
}
